﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Security.Principal;
using System.Net;

namespace SimpleMVC.Filters
{
    public class CustomAuthenticationAttribute: FilterAttribute,IAuthenticationFilter
    {
        //
        // 摘要:
        //     对请求进行身份验证。
        //
        // 参数:
        //   filterContext:
        //     用于身份验证的上下文。
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            var session = filterContext.RequestContext.HttpContext.Session;
            if (session != null && session["user"]!=null && session["roles"]!=null)
            {
                string name = session["user"].ToString();
                string[] roles = session["roles"] as string[];
                filterContext.Principal = new GenericPrincipal(new GenericIdentity(name), roles);
            }
            else
            {
                filterContext.Result = new HttpUnauthorizedResult("no authentication");
            }
        }

        //
        // 摘要:
        //     向当前 System.Web.Mvc.ActionResult 添加身份验证质询。
        //
        // 参数:
        //   filterContext:
        //     用于身份验证质询的上下文。
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            filterContext.Result = new SessionChallengeResult() { currentResult = filterContext.Result};
        }
    }
    class SessionChallengeResult : ActionResult
    {
        public ActionResult currentResult { set; get; }

        public override void ExecuteResult(ControllerContext context)
        {
            currentResult.ExecuteResult(context);
            var rsponse = context.HttpContext.Response;
            if (rsponse.StatusCode == (int)HttpStatusCode.Unauthorized)
            {
                rsponse.Redirect(string.Format("~/{0}/{1}","Account", "Login"));
                rsponse.End();
            }
        }
    }
}